package com.study.happystudy.entity;
/**
 * 返回结果类
 */

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.Data;

import java.io.Serializable;

@Data
public class ResultEntity implements Serializable {
    private Object code;//返回码
    private Object count;//返回数量
    private Object msg;//返回消息
    private Object data;//返回数据
    public ResultEntity(Object code, Object count,Object msg, Object data) {
        this.code=code;
        this.count =count;
        this.msg=msg;
        this.data = data;
    }

    /**
     * 返回成功，无参
     * @return JSON
     */
    public static  String Success() {
        return  toJson(new ResultEntity(0,null,"操作成功！",null));
    }

    /**
     * 数据查询返回成功
     * @param Res 传入的参数 Boolean 或 Int
     * @return Json
     */
    public static String Success(Object Res){
        System.out.println(Res);
        if(Res instanceof Integer){
            if((int)Res==0){
                return  toJson(new ResultEntity("1",null,"操作失败!",null));
            }else{
                return  toJson(new ResultEntity("0",null,"操作成功！",null));
            }
        }else {
            if(!((boolean) Res)){
                return  toJson(new ResultEntity("1",null,"操作失败!",null));
            }else{
                return  toJson(new ResultEntity("0",null,"操作成功！",null));
            }
        }
    }


    /**
     * 返回成功,用于Layui table
     * @param count 数量
     * @param data 内容
     * @return JSON
     */
    public static  String Success(Object count,Object data) {
        return  toJson(new ResultEntity("0",count,"操作成功！",data));
    }

    /**
     * 通用成功返回
     * @param count 数量
     * @param data 数据
     * @param code 代码
     * @param msg 信息提示
     * @return JSON
     */
    public static  String Success(Object count,Object data,Object code,Object msg) {
        return  toJson(new ResultEntity(code,count,msg,data));
    }

    /**
     * 失败返回
     * @param code 代码
     * @param msg 消息
     * @return Json
     */
    public static String Fail(Object code,Object msg){
        return toJson(new ResultEntity(code,null,msg,null));
    }

    /**
     * 失败返回
     * @param code 代码
     * @param msg 消息
     * @param data 数据
     * @return Json
     */
    public static String Fail(Object code,Object msg,Object data){
        return toJson(new ResultEntity(code,null,msg,data));
    }

    /**
     * 对象转JSON
     * @param object 对象
     * @return JSON
     */
    public static String toJson(Object object){//Object 转 json
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();
        return gson.toJson(object);
    }

    /**
     * JSON字符串转对象
     * @param json json字符串
     * @param beanClass 需要转换的类型
     * @return Object
     */
    public static Object JsonToObject(String json,Class beanClass) {
        Gson gson = new Gson();
        Object res = gson.fromJson(json, beanClass);
        return res;
    }

}
